﻿#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

#endregion

namespace WMAAN.Uzytki.Kryptografia
{
    public class GeneratorHasel
    {
        private const string litery = "abcćdeęfghijklłmnńopqrsśtuvwxyzźż";


        public static string Stworz(int minZnakow, int maxZnakow)
        {
            if (minZnakow < 0
                || maxZnakow == 0
                || maxZnakow - minZnakow < 0)
            {
                throw new ArgumentException("Niepoprawne parametry wejściowe generatora");
            }

            Random rand = new Random();

            int dlugoscHasla = rand.Next(minZnakow, maxZnakow);

            char[] maleLitery = litery.ToLower().ToCharArray();
            char[] wielkieLitery = litery.ToUpper().ToCharArray();
            char[] cyfry = "0123456789".ToCharArray();

            char[] haslo = new char[dlugoscHasla];

            for (int i = 0; i < haslo.Length; i++)
            {
                haslo[i] = '#';
            }


            for (int i = 0; i < haslo.Length; i++)
            {
                int typZnaku = rand.Next(0, 90);

                if (typZnaku >= 0 && typZnaku < 30)
                {
                    haslo[i] = maleLitery[rand.Next(0, maleLitery.Length - 1)];
                }
                else if (typZnaku >= 30 && typZnaku < 60)
                {
                    haslo[i] = wielkieLitery[rand.Next(0, wielkieLitery.Length - 1)];
                }
                else if (typZnaku >= 60 && typZnaku <= 90)
                {
                    haslo[i] = cyfry[rand.Next(0, cyfry.Length - 1)];
                }
            }
            return tablicaZnakow2String(haslo);
        }

        private static string tablicaZnakow2String(char[] tablica)
        {
            StringBuilder str = new StringBuilder(tablica.Length);
            foreach (char c in tablica)
            {
                str.Append(c);
            }
            return str.ToString();
        }

        public static bool Walidacja(string haslo)
        {
            int iloscW = 0;
            int iloscC = 0;

            char[] wielkieLitery = litery.ToUpper().ToCharArray();
            char[] cyfry = "0123456789".ToCharArray();

            char[] znakiHasla = haslo.ToCharArray();

            foreach (char z in znakiHasla)
            {
                if (zawiera(wielkieLitery, z))
                {
                    iloscW++;
                }
                else if (zawiera(cyfry, z))
                {
                    iloscC++;
                }
            }

            if(iloscW < 1 || iloscC < 1)
            {
                return false;
            }
            return true;
        }

        private static  bool zawiera(IEnumerable<char> tablica, char znak)
        {
            return tablica.Any(c => c == znak);
        }
    }
}